<template>
  <div class="app-container">
    <div style="width:100%;height:30px;display: flex; justify-content: flex-end;">
      <el-button
          size="mini"
          type="primary" round
          @click="goToBack()"
      >返回上一页
      </el-button>
    </div>
    <div style="height: 10px"></div>
    <!--<el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">-->
    <!--  <el-form-item label="批次名称" prop="planName">-->
    <!--    <el-input-->
    <!--        v-model="queryParams.planName"-->
    <!--        placeholder="请输入批次名称"-->
    <!--        clearable-->
    <!--        @keyup.enter.native="handleQuery"-->
    <!--    />-->
    <!--  </el-form-item>-->
    <!--  &lt;!&ndash;<el-form-item label="计划回款时间" prop="planDate">&ndash;&gt;-->
    <!--  &lt;!&ndash;  <el-date-picker clearable&ndash;&gt;-->
    <!--  &lt;!&ndash;                  v-model="queryParams.planDate"&ndash;&gt;-->
    <!--  &lt;!&ndash;                  type="date"&ndash;&gt;-->
    <!--  &lt;!&ndash;                  value-format="yyyy-MM-dd"&ndash;&gt;-->
    <!--  &lt;!&ndash;                  placeholder="请选择计划回款时间">&ndash;&gt;-->
    <!--  &lt;!&ndash;  </el-date-picker>&ndash;&gt;-->
    <!--  &lt;!&ndash;</el-form-item>&ndash;&gt;-->
    <!--  &lt;!&ndash;<el-form-item label="回款比例" prop="rate">&ndash;&gt;-->
    <!--  &lt;!&ndash;  <el-input&ndash;&gt;-->
    <!--  &lt;!&ndash;      v-model="queryParams.rate"&ndash;&gt;-->
    <!--  &lt;!&ndash;      placeholder="请输入回款比例"&ndash;&gt;-->
    <!--  &lt;!&ndash;      clearable&ndash;&gt;-->
    <!--  &lt;!&ndash;      @keyup.enter.native="handleQuery"&ndash;&gt;-->
    <!--  &lt;!&ndash;  />&ndash;&gt;-->
    <!--  &lt;!&ndash;</el-form-item>&ndash;&gt;-->
    <!--  <el-form-item label="回款责任人" prop="responsiblePerson">-->
    <!--    <el-input-->
    <!--        v-model="queryParams.responsiblePerson"-->
    <!--        placeholder="请输入回款责任人"-->
    <!--        clearable-->
    <!--        @keyup.enter.native="handleQuery"-->
    <!--    />-->
    <!--  </el-form-item>-->
    <!--  <el-form-item>-->
    <!--    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>-->
    <!--    <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>-->
    <!--  </el-form-item>-->
    <!--</el-form>-->

    <!--<el-row :gutter="10" class="mb8">-->
    <!--  <el-col :span="1.5">-->
    <!--    <el-button-->
    <!--        type="primary"-->
    <!--        plain-->
    <!--        icon="el-icon-plus"-->
    <!--        size="mini"-->
    <!--        @click="handleAdd"-->
    <!--        v-hasPermi="['insurance:plan:add']"-->
    <!--    >新增回款计划-->
    <!--    </el-button>-->
    <!--  </el-col>-->
    <!--  <el-col :span="1.5">-->
    <!--    <el-button-->
    <!--        type="primary"-->
    <!--        plain-->
    <!--        icon="el-icon-plus"-->
    <!--        size="mini"-->
    <!--        @click="handleAdd"-->
    <!--        v-hasPermi="['insurance:plan:add']"-->
    <!--    >新增实际回款-->
    <!--    </el-button>-->
    <!--  </el-col>-->
    <!--  &lt;!&ndash;<right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>&ndash;&gt;-->
    <!--</el-row>-->
    <el-card shadow="never" :body-style="{ height: '10px' }" :style="{
      'margin-bottom': '10px','height': tableHeight
    }">
      <el-descriptions title="回款计划">
        <template slot="extra">
          <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['insurance:plan:add']"
          >新增回款计划
          </el-button>
        </template>
      </el-descriptions>
      <el-table v-loading="loading" :data="planList" @selection-change="handleSelectionChange"
                :max-height="tableHeight1">
        <!--<el-table-column type="selection" width="55" align="center"/>-->
        <el-table-column label="批次名称" align="center" prop="planName"/>
        <el-table-column label="计划回款金额(元)" align="center" prop="planAmount"/>
        <el-table-column label="计划回款时间" align="center" prop="planDate" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.planDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="回款比例(%)" align="center" prop="rate"/>
        <el-table-column label="所需资源" align="center" prop="demand"/>
        <el-table-column label="回款责任人" align="center" prop="responsiblePerson"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120">
          <template slot-scope="scope">
            <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['insurance:plan:edit']"
            >修改
            </el-button>
            <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                style="color: red"
                @click="handleDelete(scope.row)"
                v-hasPermi="['insurance:plan:remove']"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--<pagination-->
      <!--    v-show="total>0"-->
      <!--    :total="total"-->
      <!--    :page.sync="queryParams.pageNum"-->
      <!--    :limit.sync="queryParams.pageSize"-->
      <!--    @pagination="getList"-->
      <!--/>-->
    </el-card>
    <el-card shadow="never" :body-style="{ height: '10px' }" :style="{
      'margin-bottom': '10px','height': tableHeight
    }">
      <el-descriptions title="实际回款">
        <template slot="extra">
          <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAddRel"
              v-hasPermi="['insurance:real:add']"
          >新增实际回款
          </el-button>
        </template>
      </el-descriptions>
      <el-table v-loading="loading" :data="realList" @selection-change="handleSelectionChange"
                :max-height="tableHeight1">
        <!--<el-table-column type="selection" width="55" align="center"/>-->
        <el-table-column label="批次名称" align="center" prop="realName"/>
        <el-table-column label="实际回款金额(元)" align="center" prop="realAmount"/>
        <el-table-column label="实际回款时间" align="center" prop="realDate" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.realDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="回款比例(%)" align="center" prop="rate"/>
        <el-table-column label="回款责任人" align="center" prop="responsiblePerson"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120">
          <template slot-scope="scope">
            <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdateRel(scope.row)"
                v-hasPermi="['insurance:real:edit']"
            >修改
            </el-button>
            <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                style="color: red"
                @click="handleDeleteRel(scope.row)"
                v-hasPermi="['insurance:real:remove']"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--<pagination-->
      <!--    v-show="relTotal>0"-->
      <!--    :total="relTotal"-->
      <!--    :page.sync="queryParamsRel.pageNum"-->
      <!--    :limit.sync="queryParamsRel.pageSize"-->
      <!--    @pagination="getList"-->
      <!--/>-->
    </el-card>

    <!-- 添加或修改保险合同回款计划对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="批次名称" prop="planName">
          <el-input v-model="form.planName" placeholder="请输入批次名称"/>
        </el-form-item>
        <el-form-item label="计划回款金额" prop="planAmount">
          <el-input v-model="form.planAmount" placeholder="请输入计划回款金额">
            <template slot="append">
              <el-button slot="append">元</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="计划回款时间" prop="planDate">
          <el-date-picker clearable
                          v-model="form.planDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择计划回款时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="回款比例" prop="rate">
          <el-input v-model="form.rate" placeholder="请输入回款比例">
            <template slot="append">
              <el-button slot="append">%</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="所需资源" prop="demand">
          <el-input v-model="form.demand" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="回款责任人" prop="responsiblePerson">
          <el-input v-model="form.responsiblePerson" placeholder="请输入回款责任人"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改保险合同实际回款对话框 -->
    <el-dialog :title="titleRel" :visible.sync="openRel" width="900px" append-to-body>
      <el-form ref="formRel" :model="formRel" :rules="rulesRel" label-width="100px">
        <el-form-item label="计划批次" prop="planId">
          <!--<el-input v-model="formRel.planId" placeholder="请输入计划批次id"/>-->
          <el-select v-model="formRel.planId" placeholder="请选择计划批次" @change="planChange">
            <el-option
                v-for="dict in pcList"
                :key="dict.id"
                :label="dict.planName"
                :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <!--<el-form-item label="批次名称" prop="realName">-->
        <!--  <el-input v-model="formRel.realName" placeholder="请输入批次名称"/>-->
        <!--</el-form-item>-->
        <el-form-item label="实际回款金额" prop="realAmount">
          <el-input v-model="formRel.realAmount" placeholder="请输入实际回款金额">
            <template slot="append">
              <el-button slot="append">元</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="实际回款时间" prop="realDate">
          <el-date-picker clearable
                          v-model="formRel.realDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择实际回款时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="回款比例" prop="rate">
          <el-input v-model="formRel.rate" placeholder="请输入回款比例">
            <template slot="append">
              <el-button slot="append">%</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="回款责任人" prop="responsiblePerson">
          <el-input v-model="formRel.responsiblePerson" placeholder="请输入回款责任人"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormRel">确 定</el-button>
        <el-button @click="cancelRel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listPlan, getPlan, delPlan, addPlan, updatePlan} from "@/api/insurance/premiumPlan";
import {isEmpty, isValidAmount, isValidDecimal} from "@/utils/validate";
import {addReal, delReal, getReal, listReal, updateReal} from "@/api/insurance/premiumReal";

export default {
  name: "Plan",
  data() {
    const checkPlanAmount = (rule, value, callback) => {
      if (isEmpty(value)) {
        callback();
        return
      }
      if (!isValidAmount(value)) {
        callback(new Error('请输入正确的金额'));
        return;
      }
      callback();
    }
    const checkRate = (rule, value, callback) => {
      if (isEmpty(value)) {
        callback();
        return
      }
      if (value > 100) {
        callback(new Error('回款比例不能大于100'));
        return;
      }
      if (value < 0) {
        callback(new Error('回款比例不能小于0'));
        return;
      }
      if (!isValidDecimal(value)) {
        callback(new Error('请输入正确的比例，小数不能超过2位'));
        return;
      }
      callback();
    }
    const checkPlanAmountRel = (rule, value, callback) => {
      if (isEmpty(value)) {
        callback();
        return
      }
      if (!isValidAmount(value)) {
        callback(new Error('请输入正确的金额'));
        return;
      }
      callback();
    }
    const checkRateRel = (rule, value, callback) => {
      if (isEmpty(value)) {
        callback();
        return
      }

      if (value > 100) {
        callback(new Error('回款比例不能大于100'));
        return;
      }
      if (value < 0) {
        callback(new Error('回款比例不能小于0'));
        return;
      }
      if (!isValidDecimal(value)) {
        callback(new Error('请输入正确的比例，小数不能超过2位'));
        return;
      }
      callback();
    }
    return {
      titleRel: '',
      openRel: false,
      pcList: [],
      // 表单参数
      formRel: {},
      // 表单校验
      rulesRel: {
        planId: [
          {required: true, message: "请选择批次信息", trigger: "change"}
        ],
        realAmount: [
          {validator: checkPlanAmountRel, trigger: 'blur'}
        ],
        rate: [
          {validator: checkRateRel, trigger: 'blur'}
        ]
      },
      tableHeight1: 0,
      tableHeight: 0,
      // 保险合同实际回款表格数据
      realList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 保险合同回款计划表格数据
      planList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 9999,
        insureId: null,
        contractId: null,
        planName: null,
        planAmount: null,
        planDate: null,
        rate: null,
        demand: null,
        responsiblePerson: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        planId: [
          {required: true, message: "请选择批次信息", trigger: "change"}
        ],
        planAmount: [
          {validator: checkPlanAmount, trigger: 'blur'}
        ],
        rate: [
          {validator: checkRate, trigger: 'blur'}
        ]
      },
      contractId: undefined,
      insureId: undefined
    };
  },
  created() {
    this.contractId = this.$route.query.contractId
    this.insureId = this.$route.query.insureId
    if (isEmpty(this.contractId) || isEmpty(this.insureId)) {
      this.$modal.msgWarning('缺少必要参数，请重新进入页面')
      return
    }
    this.getList();
  },
  mounted() {
    this.$nextTick(() => {
      let tableHeight = (window.innerHeight - 180) / 2
      this.tableHeight1 = tableHeight-75
      this.tableHeight = tableHeight + 'px'
    })
  },
  methods: {
    planChange(row) {
      let pc = this.pcList.find(item => item.id == row)
      this.formRel.planName = pc.planName
    },
    // 表单重置
    resetRel() {
      this.formRel = {
        id: null,
        insureId: null,
        contractId: null,
        planId: null,
        realName: null,
        realAmount: null,
        realDate: null,
        rate: null,
        responsiblePerson: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("formRel");
    },
    /** 新增按钮操作 */
    handleAddRel() {
      const param = {}
      param.contractId = this.contractId
      param.insureId = this.insureId
      param.pageSize = 9999
      param.pageNum = 1
      listPlan(param).then(response => {
        this.reset();
        this.openRel = true;
        this.pcList = response.rows
      })
      this.titleRel = "添加保险合同实际回款";
    },
    /** 修改按钮操作 */
    handleUpdateRel(row) {
      this.reset();
      const id = row.id || this.ids
      const param = {}
      param.contractId = this.contractId
      param.insureId = this.insureId
      param.pageSize = 9999
      param.pageNum = 1
      listPlan(param).then(response => {
        this.reset();
        this.pcList = response.rows
        getReal(id).then(response => {
          this.formRel = response.data;
          this.openRel = true;
          this.titleRel = "修改保险合同实际回款";
        });
      })
    },
    /** 提交按钮 */
    submitFormRel() {
      this.$refs["formRel"].validate(valid => {
        if (valid) {
          this.formRel.contractId = this.contractId
          this.formRel.insureId = this.insureId
          if (this.formRel.id != null) {
            updateReal(this.formRel).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.openRel = false;
              this.getList();
            });
          } else {
            addReal(this.formRel).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.openRel = false;
              this.getList();
            });
          }
        }
      });
    },
    // 取消按钮
    cancelRel() {
      this.openRel = false;
      this.resetRel();
    },
    /** 删除按钮操作 */
    handleDeleteRel(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除选中的保险合同实际回款？').then(function () {
        return delReal(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    goToBack() {
      this.$router.push({path: "/bxht/contract"});
    },
    /** 查询保险合同回款计划列表 */
    getList() {
      this.loading = true;
      this.queryParams.contractId = this.contractId
      this.queryParams.insureId = this.insureId
      listPlan(this.queryParams).then(response => {
        this.planList = response.rows;
        // this.total = response.total;
        this.loading = false;
      });
      listReal(this.queryParams).then(response => {
        this.realList = response.rows;
        // this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        insureId: null,
        contractId: null,
        planName: null,
        planAmount: null,
        planDate: null,
        rate: null,
        demand: null,
        responsiblePerson: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加保险合同回款计划";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getPlan(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改保险合同回款计划";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.contractId = this.contractId
          this.form.insureId = this.insureId
          if (this.form.id != null) {
            updatePlan(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPlan(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除选中的保险合同回款计划？').then(function () {
        return delPlan(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('insurance/plan/export', {
        ...this.queryParams
      }, `plan_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-descriptions {
  &:not(:nth-child(1)) {
    margin-top: 20px;
  }

  .el-descriptions__title {
    display: flex;
    align-items: center;

    &::before {
      display: inline-block;
      width: 3px;
      height: 20px;
      margin-right: 10px;
      background-color: #409eff;
      content: '';
    }
  }

  .el-descriptions-item__container {
    margin: 0 10px;

    .no-colon {
      margin: 0;

      &::after {
        content: '';
      }
    }
  }
}
</style>
